package com.ruoyi.project.pest.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.project.pest.service.PestDetectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 病虫害识别控制器
 */
@RestController
@RequestMapping("/pest/detection")
public class PestDetectionController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(PestDetectionController.class);

    @Autowired
    private PestDetectionService pestDetectionService;

    /**
     * 病虫害检测
     */
    @PostMapping("/detect")
    public AjaxResult detectPest(@RequestParam("imageFile") MultipartFile imageFile) {
        log.info("收到病虫害检测请求，文件名: {}，大小: {} bytes",
                imageFile.getOriginalFilename(), imageFile.getSize());

        try {
            // 验证文件
            if (imageFile.isEmpty()) {
                return AjaxResult.error("请选择要上传的图片");
            }

            // 检查文件类型
            String contentType = imageFile.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return AjaxResult.error("请上传有效的图片文件");
            }

            // 检查文件大小 (限制为10MB)
            if (imageFile.getSize() > 10 * 1024 * 1024) {
                return AjaxResult.error("图片大小不能超过10MB");
            }

            // 调用检测服务
            Map<String, Object> result = pestDetectionService.detectPest(imageFile);

            // 检查Python服务返回的结果
            if (Boolean.TRUE.equals(result.get("success"))) {
                log.info("病虫害检测成功");
                return AjaxResult.success("检测成功", result);
            } else {
                String errorMsg = (String) result.getOrDefault("error", "检测失败");
                log.error("病虫害检测失败: {}", errorMsg);
                return AjaxResult.error(errorMsg);
            }

        } catch (Exception e) {
            log.error("病虫害检测失败", e);
            return AjaxResult.error("检测失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public AjaxResult checkHealth() {
        try {
            boolean isHealthy = pestDetectionService.isServiceHealthy();
            if (isHealthy) {
                return AjaxResult.success("Python服务运行正常", true);
            } else {
                return AjaxResult.error("Python服务不可用", false);
            }
        } catch (Exception e) {
            log.error("服务健康检查失败", e);
            return AjaxResult.error("服务健康检查失败: " + e.getMessage());
        }
    }

    /**
     * 测试检测功能
     */
    @GetMapping("/test")
    public AjaxResult testDetection() {
        try {
            Map<String, Object> result = pestDetectionService.testDetection();

            if (Boolean.TRUE.equals(result.get("success"))) {
                return AjaxResult.success("测试检测成功", result);
            } else {
                String errorMsg = (String) result.getOrDefault("error", "测试检测失败");
                return AjaxResult.error(errorMsg);
            }

        } catch (Exception e) {
            log.error("测试检测功能失败", e);
            return AjaxResult.error("测试检测功能失败: " + e.getMessage());
        }
    }
}
